﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Data;
using SmartSpace.Core;
using System.Threading;
using System.IO;
using SmartSpace.Packaging;

namespace SsTool.Install
{
    /// <summary>
    /// Interaction logic for ImportOrgMemberFromExcel.xaml
    /// </summary>
    public partial class ImportOrgMemberFromExcel : Page
    {
        private string _filePath;

        public ImportOrgMemberFromExcel()
        {
            InitializeComponent();
        }

        private void _ctlBtnBroswer_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "excel(*.xlsx)|*.xlsx";
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == true)
            {
                _ctlBtnBroswer.Content = dlg.FileName;
                _filePath = dlg.FileName;

                ExcelUtil util = new ExcelUtil(_filePath);
                _ctlListSheets.ItemsSource = util.GetSheets();
                util.Close();
            }
        }

        private void _ctlListSheets_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string sheetName = e.AddedItems[0].ToString();

            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(sheetName, 20);
            util.Close();

            List<string> columns = new List<string>();
            foreach (DataColumn item in table.Columns)
            {
                columns.Add(item.ColumnName);
            }

            _ctlListAccount.ItemsSource = columns;
            _ctlListOrgCode.ItemsSource = columns;
        }

        private void _ctlBtnImport_Click(object sender, RoutedEventArgs e)
        {
            string accountColumn = _ctlListAccount.SelectedItem.ToString();
            string orgCodeColumn = _ctlListOrgCode.SelectedItem.ToString();

            string sheetName = _ctlListSheets.SelectedItem.ToString();


            Thread thread = new Thread(new ParameterizedThreadStart(Importing));
            this.IsEnabled = false;
            _ctlOutput.Text = "开始导入";
            thread.Start(new string[] { accountColumn, orgCodeColumn, sheetName });
        }

        private void Importing(object p)
        {
            string[] args = (string[])p;

            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(args[2]);
            util.Close();

            ICoreService coreService = App.Get<ICoreService>();

            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];
                string account = Convert.ToString(row[args[0]]);
                string orgCode = Convert.ToString(row[args[1]]);

                if (!string.IsNullOrEmpty(account) && !string.IsNullOrEmpty(orgCode))
                {
                    User user = coreService.GetUser(account);
                    if (user != null)
                    {
                        Org org = coreService.GetOrg(orgCode);
                        if (org != null)
                        {
                            if (coreService.AddMember(org, user, true))
                            {
                                Dispatcher.Invoke(
                                    new Action<User, Org>(Render),
                                    user,
                                    org);
                            }
                            else
                            {
                                Dispatcher.Invoke(
                                    new Action<string>(Render),
                                    string.Format("关联用户{0}到部门{1}失败!{2}", user.Name, org.Caption, Environment.NewLine));
                            }
                        }
                        else
                        {
                            Dispatcher.Invoke(
                                new Action<string>(Render),
                                string.Format("关联用户{0}失败,部门{1}不存在!{2}", user.Name, orgCode, Environment.NewLine));
                        }
                    }
                    else
                    {
                        Dispatcher.Invoke(
                            new Action<string>(Render),
                            string.Format("关联用户{0}失败,用户{0}不存在!{1}", user.Name,Environment.NewLine));
                    }
                }
            }
            MessageBox.Show("导入完毕");
            Dispatcher.Invoke(new Action(Finish));
        }

        private void Render(User user, Org org)
        {
            _ctlOutput.Text += string.Format("关联用户{0}到部门{1}成功!{2}", user.Name, org.Caption, Environment.NewLine);
            _ctlOutput.ScrollToEnd();
        }

        private void Render(string message)
        {
            _ctlOutput.Text += message;
            _ctlOutput.ScrollToEnd();
        }

        private void Finish()
        {
            _ctlOutput.Text += "导入完成";
            _ctlOutput.ScrollToEnd();
            this.IsEnabled = true;
        }

        #region 导出到Xml
        private void _ctlBtnImportXml_Click(object sender, RoutedEventArgs e)
        {
            string accountColumn = _ctlListAccount.SelectedItem.ToString();
            string orgCodeColumn = _ctlListOrgCode.SelectedItem.ToString();

            string sheetName = _ctlListSheets.SelectedItem.ToString();


            Thread thread = new Thread(new ParameterizedThreadStart(ImportingXml));
            this.IsEnabled = false;
            _ctlOutput.Text = "开始导入";
            thread.Start(new string[] { accountColumn, orgCodeColumn, sheetName });
        }

        private void ImportingXml(object p)
        {
            string[] args = (string[])p;

            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(args[2]);
            util.Close();

            List<OrgMember> members = new List<OrgMember>();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];
                string account = Convert.ToString(row[args[0]]);
                string orgCode = Convert.ToString(row[args[1]]);

                if (!string.IsNullOrEmpty(account) && !string.IsNullOrEmpty(orgCode))
                {
                    bool isExist = false;
                    foreach (var item in members)
                    {
                        if (item.Org.Code == orgCode && item.User.Account == account)
                        {
                            isExist = true;
                            break;
                        }
                    }

                    if (!isExist)
                    {
                        OrgMember member = new OrgMember();
                        member.Id = Guid.NewGuid();
                        member.IsMajor = true;
                        member.Org = new Org();
                        member.Org.Code = orgCode;
                        member.User = new User();
                        member.User.Account = account;
                        members.Add(member);

                        Dispatcher.Invoke(
                               new Action<string>(Render),
                               string.Format("关联用户{0}和单位{1}!{2}", member.User.Account, member.Org.Code, Environment.NewLine));
                    }
                }
            }

            FileInfo fi = new FileInfo(_filePath);
            string xmlFileName = fi.Name.Replace(fi.Extension, string.Empty);
            string xmlFilePath = fi.Directory.FullName + "\\" + xmlFileName + "(member).xml";
            XMemberUtil.Save(members, xmlFilePath);
            Dispatcher.Invoke(new Action<string>(Finish2), xmlFilePath);
        }
   
        private void Finish2(string path)
        {
            _ctlOutput.Text += "导入完成:" + path;
            _ctlOutput.ScrollToEnd();
            this.IsEnabled = true;
        }
        #endregion
    }
}
